/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.seata.gateway.config;

import cn.denvie.springcloud.seata.gateway.properties.NotAuthUrlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.Collections;

/**
 * GatewayConfig。
 *
 * @author Denvie
 * @date 2022/4/9
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(NotAuthUrlProperties.class)
public class GatewayConfig {
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //@LoadBalancer
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 此处不能直接通过 @LoadBalancer 配置 RestTemplate 去获取公钥
        // 因为 @LoadBalancer 是通过 SmartInitializingSingleton 形式注入负载均衡器的，
        // 而 SmartInitializingSingleton 是在所有的非懒加载单例bean构建完成之后才调用，
        // 所以 AuthenticationGlobalFilter.afterPropertiesSet() 中通过 RestTemplate 去调用微服务会报错
        restTemplate.setInterceptors(
                Collections.singletonList(new LoadBalancerInterceptor(loadBalancerClient)));
        return restTemplate;
    }

    //@Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}
